package com.ykl.utils;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.Locale;

public final class HttpDownloadHeaderUtils {

    public static void writeFileHeaders(String filename, String contentType, HttpServletRequest req, HttpServletResponse resp) {
        String encoding = req.getCharacterEncoding();
        Locale locale = req.getLocale();
        resp.setCharacterEncoding(encoding);
        resp.setLocale(locale);
        resp.setContentType(contentType);
    }

    public static void writeAttachmentHeaders(String filename, HttpServletRequest req, HttpServletResponse resp) {
        resp.setContentType("application/octet-stream");
        writeFileHeaders(filename, "application/octet-stream", req, resp);
        String strHttpHeaderReqAgent = req.getHeader("user-agent");
        if (StringUtils.containsIgnoreCase(strHttpHeaderReqAgent, "iphone")) {
            filename = new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        } else if (StringUtils.containsIgnoreCase(strHttpHeaderReqAgent, "android")) {
            filename = UrlEncoderUtils.encode(filename);
        } else if (StringUtils.containsIgnoreCase(strHttpHeaderReqAgent, "chrome")) {
            filename = UrlEncoderUtils.encode(filename);
        } else if (StringUtils.containsIgnoreCase(strHttpHeaderReqAgent, "edge")) {
            filename = UrlEncoderUtils.encode(filename);
        } else if (StringUtils.containsIgnoreCase(strHttpHeaderReqAgent, "Trident")) {
            filename = UrlEncoderUtils.encode(filename);
        } else if (StringUtils.containsIgnoreCase(strHttpHeaderReqAgent, "firefox")) {
            filename = "=?utf-8?b?" + Arrays.toString(Base64.getEncoder().encode(filename.getBytes(StandardCharsets.UTF_8))) + "?=";
        }

        resp.setHeader("Content-Disposition", "attachment;filename=" + filename);
    }
}

